<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

/**
 * 文化配送排班表
 * Class ReservationScheduleModel
 * @package app\common\model
 */
class ReservationSchedule extends BaseModel
{
    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    public $table = 'reservation_schedule';


    /**
     * 预约排版信息
     * @param  $reservation_id 预约id
     */
    public function lists($reservation_id)
    {
        $res = $this->select('id', 'week', 'start_time', 'end_time')
            ->where("reservation_id", $reservation_id)
            ->where('is_del', 1)
            ->get()
            ->toArray();

        //查询当前预约展示时间
        $reservation_model = new Reservation();
        $scheduleSpecialModel = new ReservationSpecialSchedule();
        $reservation = $reservation_model->where('id', $reservation_id)->first();
        $display_day = !empty($reservation['display_day']) ? $reservation['display_day'] : 7;
        $day_data = get_behind_date('', $display_day);
        //  dump($day_data);die;
        $res_data = [];
        foreach ($day_data as $key => $val) {
            $week_index = date("w", strtotime($val)) ? date("w", strtotime($val)) : 7;
            //查询是否有特殊日期
            $special_data = $scheduleSpecialModel->getSpecialListByDate($reservation_id, $val, ['id', 'date', 'start_time', 'end_time']);
            if ($special_data) {
                //存在特殊日期
                foreach ($special_data as $k => $v) {
                    $special_data[$k]['week'] = $week_index;
                    $special_data[$k]['schedule_type'] = 2; //特殊日期
                }
                $res_data[date("m-d", strtotime($val)) . " [" . get_week_name($week_index) . "] 特殊"] = $special_data;
            } else {
                foreach ($res as $k => $v) {
                    if ($v['week'] == $week_index) {
                        $v['schedule_type'] = 1;
                        $v['date'] = date('Y-m-d', strtotime($val));
                        $res_data[date("m-d", strtotime($val)) . " (" . get_week_name($week_index) . ") "][] = $v;
                        continue;
                    }
                }
            }
        }

        return $res_data;
    }
    /**
     * 获取指定预约id列表
     **/
    public function getScheduleList($reservation_id, $week = "", $field = "*")
    {
        $res = $this->select($field)
            ->where('is_del', 1)
            ->where('reservation_id', $reservation_id)
            ->where(function ($query) use ($week) {
                if ($week) {
                    $query->where('week', $week);
                }
            })
            ->groupBy('start_time')
            ->get()
            ->toArray();

        return $res;
    }


    /**
     * 添加预约排班信息
     * $week  json 格式数据
     *        数组样式  ['day'=>1,'time'=>[['start_time'=>'15:12:12' , 'end_time'=>'16:12:12'],['start_time'=>'15:12:12' , 'end_time'=>'16:12:12']];
     */
    public function add($week, $reservation_id = '')
    {
        if (is_string($week)) {
            $week = json_decode($week, true);
        }
        $weekData = [];
        foreach ($week as $key => $val) {
            foreach ($val['time'] as $k => $v) {
                if ($v['start_time'] >= $v['end_time']) {
                    throw new Exception('排版时间设置有误，开始时间不能大于等于结束时间');
                }
                $temp['reservation_id'] = $reservation_id;
                $temp['week'] = $val['day'];
                $temp['start_time'] = $v['start_time'];
                $temp['end_time'] = $v['end_time'];
                $temp['create_time'] = date("Y-m-d H:i:s", time());
                $weekData[] = $temp;
            }
        }

        $this->insert($weekData);
    }

    /**
     * 修改预约排班信息
     */
    public function change($week, $reservation_id = '', $findWhere = [])
    {
        if (is_string($week)) $week = json_decode($week, true);
        //先删除所有，后面在恢复
        $delete_schedule_id = $this->where('reservation_id', $reservation_id)->where('is_del', 1)->pluck('id')->toArray(); //删除的排版id,防止出现之前删除的，这次又恢复了
        $this->whereIn('id', $delete_schedule_id)->update(['is_del' => 2, 'change_time' => date('Y-m-d H:i:s')]);
        $weekData = [];
        foreach ($week as $key => $val) {
            foreach ($val['time'] as $k => $v) {
                if ($v['start_time'] >= $v['end_time']) {
                    throw new Exception('排版时间设置有误，开始时间不能大于等于结束时间');
                }
                $temp['reservation_id'] = $reservation_id;
                $temp['week'] = $val['day'];
                $temp['start_time'] = $v['start_time'];
                $temp['end_time'] = $v['end_time'];
                $temp['create_time'] = date("Y-m-d H:i:s", time());

                $is_repeat = $this->where('week', $val['day'])
                    ->where('reservation_id', $reservation_id)
                    ->where('start_time', $v['start_time'])
                    ->where('end_time', $v['end_time'])
                    ->whereIn('id', $delete_schedule_id)
                    ->orderByDesc('create_time')
                    ->first();

                if ($is_repeat) {
                    $this->where('id', $is_repeat->id)->update(['is_del' => 1, 'change_time' => null]);
                } else {
                    $weekData[] = $temp;
                }
            }
        }

        $this->insert($weekData);
    }


    /**
     * 检查排班数据是否更新
     */
    public function checkScheduleIsChange($new_data, $id)
    {
        if (is_string($new_data))  $new_data = json_decode($new_data, true);

        $week = [];
        $schedule_id_arr = []; //需要删除的排版id
        for ($i = 1; $i <= 7; $i++) {
            $old_day_data = $this->select('id', 'start_time', 'end_time')->where('week', $i)->where('reservation_id', $id)->where('is_del', 1)->get()->toArray();
            if (!empty($new_data[$i - 1]['time'])) {
                if (count($new_data[$i - 1]['time']) != count($old_day_data)) {
                    $week[] = $i;
                }
                foreach ($new_data[$i - 1]['time'] as $key => $val) {
                    foreach ($old_day_data as $old_key => $old_value) {
                        if ($val['start_time'] == date("H:i:s", strtotime($old_value['start_time'])) && $val['end_time'] == date("H:i:s", strtotime($old_value['end_time']))) {
                            unset($old_day_data[$old_key]);
                        }
                    }
                }
            }
            if (!empty($old_day_data)) {
                $week[] = $i;
                $schedule_ids = array_column($old_day_data, 'id');
                foreach ($schedule_ids as $v) {
                    $schedule_id_arr[] = $v;
                }
            }
        }
        $week = array_unique($week);
        $schedule_id_arr = array_unique($schedule_id_arr);
        return [$week, $schedule_id_arr];
    }
    /**
     * 获取当前日期，时间段内的排版信息 （扫码时使用）
     * @param $reservation_id
     */
    public function getWeekScheduleInfo($reservation_id, $weeks, $field = [])
    {
        if (empty($field)) {
            $field = ["id", "week", "start_time", "end_time", "reservation_id"];
        }
        $reservation_schedule = $this->select($field)
            ->where('week', $weeks)
            ->where(function ($query) use ($reservation_id) {
                if ($reservation_id) {
                    $query->where('reservation_id', $reservation_id);
                }
            })
            ->where('is_del', 1)
            ->where('start_time', '<', date('H:i:s', time() + 600)) //可以提前 10 分钟进去
            ->where('end_time', '>', date('H:i:s'))
            ->get()
            ->toArray();

        return $reservation_schedule;
    }

    /**
     * 获取排版数据
     */
    public function getReservationSchedule($reservation_id, $weeks)
    {
        $reservationSpecialScheduleModel = new ReservationSpecialSchedule();
        $reservation_schedule = $reservationSpecialScheduleModel->getSpecialScheduleInfo($reservation_id, date('Y-m-d'));
        $schedule_type = 2; //默认特殊
        if (empty($reservation_schedule)) {
            //获取当前时间段对应的  预约时间段信息
            $reservationScheduleModel = new ReservationSchedule();
            $reservation_schedule = $reservationScheduleModel->getWeekScheduleInfo($reservation_id, $weeks);
            $schedule_type = 1;
        }
        if (empty($reservation_schedule)) {
            return [false, "当前时间段，无任何排版信息"];
        } else {
            $reservation_schedule = $reservation_schedule[0]; //返回的是一个二维数组 
        }
        return [$schedule_type, $reservation_schedule];
    }
}
